package com.xiaobao.campusLostFoundAfter.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.UUID;

public class OssImageUploader {
    @Value("${aliyun.oss.endpoint}")
    private final String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private final String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private final String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private final String bucketName;
    @Value("${aliyun.oss.urlPrefix}")
    private final String urlPrefix;

    public OssImageUploader(String endpoint, String accessKeyId, String accessKeySecret,
                            String bucketName, String urlPrefix) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
        this.urlPrefix = urlPrefix;
    }

    /**
     * 上传图片到OSS并返回URL
     *
     * @param file 图片文件
     * @return 图片URL，失败时返回null
     */
    public String uploadImage(MultipartFile file) {
        // 参数校验
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("请上传图片文件");
        }

        OSS ossClient = null;
        try {
            // 创建OSS客户端
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new IOException("文件名为空");
            }
            String fileName = UUID.randomUUID() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

            // 创建日期目录结构
            String folder = "images/" + LocalDate.now() + "/";
            fileName = folder + fileName;

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传文件
            ossClient.putObject(new PutObjectRequest(bucketName, fileName, inputStream));

            // 返回访问URL
            return urlPrefix + "/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传图片失败", e);
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 批量上传图片并返回URL数组
     */
    public String[] batchUploadImages(MultipartFile[] files) {
        if (files == null || files.length == 0) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        String[] urls = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            urls[i] = uploadImage(files[i]);
        }

        return urls;
    }
}
